package v1

import (
	"net/http"

	"gitee.com/daonna/collab-manage-system/service"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

// UserLogin handles the user login request
func Login(c *gin.Context) {
	var req service.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	user, accessToken, refreshToken, err := service.LoginUser(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "登录失败: " + err.Error(),
		})
		logrus.Error("login failed: ", err)
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "登录成功",
		"data": gin.H{
			"access_token":  accessToken,
			"refresh_token": refreshToken,
			"user": gin.H{
				"id":           user.ID,
				"username":     user.Username,
				"display_name": user.DisplayName,
				"avatar_url":   user.AvatarURL,
				"email":        user.Email,
			},
		},
	})
}

// UserLogout 登出
func UserLogout(c *gin.Context) {
	// 登出逻辑通常包括使当前的 token 失效
	c.JSON(http.StatusOK, gin.H{"message": "Successfully logged out"})
}

// RegisterByEmail 注册
func RegisterByEmail(c *gin.Context) {
	var registerReq service.RegisterRequest
	if err := c.ShouldBindJSON(&registerReq); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}

	user, err := service.RegisterUserByEmail(c.Request.Context(), registerReq)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Registration failed", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Registration successful", "user": user})
}

// ForgotPassword 忘记密码
func ForgotPassword(c *gin.Context) {
	var req service.PasswordResetRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
		return
	}

	err := service.ResetPassword(c.Request.Context(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Password reset failed", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Password reset email sent"})
}

// v1/user.go
func GetUserList(c *gin.Context) {
	users, err := service.GetAllUsers(c.Request.Context())
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to retrieve users", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"users": users})
}
